#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>

#include <iostream>
using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_openDBButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Open sqlite database"), "", tr("Sqlite (* *.sqlite)"));
    
    ui->label->setText("");
    ui->listWidget->clear();
    
    ui->tableWidget->clear();
    ui->tableWidget->setRowCount(0);
    ui->tableWidget->setColumnCount(0);
    
    if (!db.openDatabase(fileName) || db.getTables().count() == 0)
    {
        ui->label->setText("No tables found or Invalid SQLite file");
    }else
    {
        ui->label->setText("Database loaded [" + fileName + "]");
        QStringList tables = db.getTables();
        ui->listWidget->addItems(tables);
    }
}

void MainWindow::on_listWidget_itemClicked(QListWidgetItem *item)
{
    QString tableName = item->text();
    
    QList<QStringList> resultList = db.getResultForTable(tableName);
    
    if (resultList.size() >= 1)
    {
        int rowCount = resultList.size();
        int colsCount = resultList.at(0).size();
        
        ui->tableWidget->setRowCount(rowCount-1);
        ui->tableWidget->setColumnCount(colsCount);
        
        
        for (int i=0; i<rowCount ; i++)
        {
            QStringList row = resultList.at(i);
            
            for (int j=0; j<colsCount; j++)
            {
                QTableWidgetItem *cellValue = new QTableWidgetItem(row.at(j));
                cellValue->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
                
                if (i%2==1)
                {
                    cellValue->setBackground(QBrush(QColor(150, 150, 250)));
                    cellValue->setForeground(QBrush(QColor("white")));
                }
                
                if (i ==0)
                    ui->tableWidget->setHorizontalHeaderItem(j, cellValue);
                else
                    ui->tableWidget->setItem(i-1, j, cellValue);
            }
        }    
    }else
    {
        ui->tableWidget->setColumnCount(0);
        ui->tableWidget->setRowCount(0);
    }   
}
